package stark.app.function.appwidget;

import android.os.Build;
import android.util.Log;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.appwidget.lib.AppWidgetAdder;

import stark.app.R;
import stark.app.databinding.ActivityAppWidgetDemoBinding;
import stark.common.basic.base.BaseNoModelActivity;
import stark.common.basic.device.BatteryUtil;
import stark.common.basic.utils.DialogUtil;
import stark.common.basic.utils.FastClickUtil;

/**
 * Author：daizhongbin on 2023/1/6
 * Email：1027154338@qq.com
 * Desc:
 */
public class AppWidgetDemoActivity extends BaseNoModelActivity<ActivityAppWidgetDemoBinding> {

    @Override
    protected int onCreate() {
        return R.layout.activity_app_widget_demo;
    }

    @Override
    protected void initView() {
        mDataBinding.btnAdd.setOnClickListener(v -> {
            if (FastClickUtil.isFastClick()) {
                return;
            }
            boolean ret = AppWidgetAdder.getInstance().addAppWidget(R.layout.test_app_widget, TestAppWidget.class);
            Log.e("dzb", "ret = " + ret);
        });
    }

    @Override
    protected void initData() {
        AppWidgetAdder.getInstance().init();
        AppWidgetAdder.getInstance().setCreateAppWidgetViewListener((layoutId, appWidgetId) -> {
            showTipDialog();
            return new TestAppWidgetView(appWidgetId);
        });

        //要想应用能够接收到开机广播自启动，需具备以下两个条件，1、申请到悬浮窗权限 2、请求忽略电池优化(荣耀pro20手机实际测试到可以不用申请悬浮窗权限也能收到开机广播)
        //1、申请悬浮窗权限(如果权限请求被用户拒绝，是否每次进来都要请求请开发人员自己做处理，这里只是demo，直接每次都请求了)
        reqPermission();
        //2、请求忽略电池优化(如果请求被用户拒绝，是否每次进来都要请求请开发人员自己做处理，这里只是demo，直接每次都请求了)
        BatteryUtil.reqIgnoreBatteryOptimizations(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppWidgetAdder.getInstance().deInit();
    }

    private void reqPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!PermissionUtils.isGrantedDrawOverlays()) {
                PermissionUtils.requestDrawOverlays(new PermissionUtils.SimpleCallback() {
                    @Override
                    public void onGranted() {
                    }

                    @Override
                    public void onDenied() {
                    }
                });
            }
        }
    }

    private void showTipDialog() {
        DialogUtil.asConfirm(this, "", "添加小组件成功", "我知道了", null);
    }
}
